package com.raycloud.java.dada.base;

import com.raycloud.java.dada.annotation.ParamValue;
import com.raycloud.java.dada.exception.DadaServiceException;
import com.raycloud.java.dada.util.ObjecToJson;
import com.raycloud.java.dada.util.SignatureUtil;

import java.lang.reflect.Field;
import java.util.*;


/**
 * Created by:  intelliJ IDEA
 *
 * @Author albert
 * @Description:基础参数+请求参数
 * @Date:2017/6/21 下午1:53
 * @package:com.raycloud.java.dada.service
 * @Modified By:
 */
public class ParamService {

    private String appKey;
    private String appSecret;

    public ParamService(String appKey, String appSecret) {
        this.appKey = appKey;
        this.appSecret = appSecret;

    }

    /**
     * 将对象按照注解转换为Map
     *
     * @param object
     * @return
     * @throws Exception
     */
    public Map<String, Object> createParam(Object object, String sourceId) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
       boolean check = parametersCheck(object);
       if (check && object != null){
           List<Field> fields = Arrays.asList(object.getClass().getDeclaredFields());
           try {
                fieldValue(fields,object,paramMap);
           } catch (IllegalAccessException ex) {
               throw new Exception("对象转参数时出错了，请检查");
           } catch (Exception e) {
               throw new Exception("class ParamService method createParam 异常");
           }
       }
        Map<String, Object> param = baseParamMap(ObjecToJson.toJson(paramMap), sourceId);
        String sign = SignatureUtil.sortDicByKey(param, appSecret);
        param.put("signature", sign);
        return param;
    }


    /**
     * 将对象按照注解转换为Map 支持数组传入
     *
     * @param objects
     * @return
     * @throws Exception
     */
    public Map<String, Object> createParams(List<Object> objects, String sourceId) throws Exception {
        List<Object> paramObj = new ArrayList<Object>();
        for (Object object : objects) {
            boolean check = parametersCheck(object);
            Map<String, Object> paramMap = new HashMap<String, Object>();
            if (check && object !=null){
                List<Field> fields = Arrays.asList(object.getClass().getDeclaredFields());
                try {
                    fieldValue(fields,object,paramMap);
                    paramObj.add(paramMap);
                } catch (IllegalAccessException ex) {
                    throw new Exception("对象转参数时出错了，请检查");
                } catch (Exception e) {
                    throw new Exception("class ParamService method createParam 异常");
                }
            }else{
                continue;
            }
        }

        Map<String, Object> param = baseParamMap(ObjecToJson.toJson(paramObj), sourceId);
        String sign = SignatureUtil.sortDicByKey(param, appSecret);
        param.put("signature", sign);
        return param;
    }


    private Map<String, Object> fieldValue(List<Field> fields,Object object,
                                           Map<String,Object> paramMap) throws IllegalAccessException{
        for (Field field : fields) {
            //是否使用了参数注解值
            if (field.isAnnotationPresent(ParamValue.class)) {
                //获取属性上的注解
                ParamValue paramValue = field.getAnnotation(ParamValue.class);
                //获取属性值
                field.setAccessible(true);
                Object val = field.get(object);
                if (val != null)
                    paramMap.put(paramValue.filedName(), val);
            }
        }
        return paramMap;
    }


    /**
     * 基础参数+接口参数
     *
     * @param aipParamJson
     * @param sourceId     商户id
     * @return
     * @throws Exception
     */
    private Map<String, Object> baseParamMap(String aipParamJson, String sourceId) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("app_key", appKey);
        paramMap.put("timestamp", System.currentTimeMillis() / 1000);
        paramMap.put("format", "json");
        paramMap.put("v", "1.0");
        paramMap.put("source_id", sourceId);
        paramMap.put("body", aipParamJson);
        return paramMap;
    }

    /**
     * 接口参数校验
     * @param object
     * @return
     * @throws DadaServiceException
     */
    public boolean parametersCheck(Object object) throws DadaServiceException {
        StringBuilder sbl = new StringBuilder();
        if (object != null) {
            List<Field> fields = Arrays.asList(object.getClass().getDeclaredFields());
            try {
                for (Field field : fields) {
                    if (field.isAnnotationPresent(ParamValue.class)) {
                        ParamValue paramValue = field.getAnnotation(ParamValue.class);
                        if (paramValue.isNotNull()) {
                            //获取属性值
                            field.setAccessible(true);
                            Object val = field.get(object);
                            if ("".equals(val) || null == val) {
                                sbl.append("业务参数");
                                sbl.append(paramValue.filedName()).append("不能为空;\n");
                            }
                        }
                    }
                }
                if (sbl.toString() != null && !"".equalsIgnoreCase(sbl.toString())){
                    throw new DadaServiceException(sbl.toString());
                }
            } catch (IllegalAccessException el) {
                throw new DadaServiceException("参数校验异常" + el.getMessage());
            }
        }
        return true;
    }
}
